package com.lhy.admin.util;

/**
 * JacksonUtil
 *
 * @author hyluan
 * @date 2022年08月02日 12:28
 */

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * Jackson工具类
 */
@Slf4j
public class JacksonUtil {

    private static ObjectMapper mapper() {
        ObjectMapper bean = null;
        try {
            bean = SpringContextUtil.getBean(ObjectMapper.class);
        } catch (Exception e) {
            bean = new ObjectMapper();
        }
        return bean;
    }

    public static String bean2Json(Object data) {
        try {
            String result = mapper().writeValueAsString(data);
            return result;
        } catch (JsonProcessingException e) {
            log.error("", e);
        }
        return null;
    }

    public static <T> T json2Bean(String jsonData, Class<T> beanType) {
        try {
            T result = mapper().readValue(jsonData, beanType);
            return result;
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    public static <T> List<T> json2List(String jsonData, Class<T> beanType) {
        JavaType javaType = mapper().getTypeFactory().constructParametricType(List.class, beanType);
        try {
            return mapper().readValue(jsonData, javaType);
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    public static <K, V> Map<K, V> json2Map(String jsonData, Class<K> keyType, Class<V> valueType) {
        JavaType javaType = mapper().getTypeFactory().constructMapType(Map.class, keyType, valueType);
        try {
            return mapper().readValue(jsonData, javaType);
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    public static <T> T json2Bean(String jsonData, TypeReference<T> typeReference) {
        try {
            return mapper().readValue(jsonData, typeReference);
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    public static JsonNode json2Node(String jsonData) {
        try {
            return mapper().readTree(jsonData);
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }


}
